package com.xinqi.modules.course.classroom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.core.constant.Constants;
import com.xinqi.common.core.enums.AssistantTypeEnum;
import com.xinqi.common.core.enums.ClassRoleEnum;
import com.xinqi.common.core.enums.InteractiveEnum;
import com.xinqi.common.core.enums.SysMessageEnum;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.modules.chat.chat.official.client.ChatAssistantContentClient;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentCreateDTO;
import com.xinqi.modules.chat.chat.official.json.QuestionsMessage;
import com.xinqi.modules.chat.chat.rongyun.RemoteRongyunClient;
import com.xinqi.modules.course.classromm.dto.InterationQueryDTO;
import com.xinqi.modules.course.classromm.dto.LiveActCreateDTO;
import com.xinqi.modules.course.classromm.dto.NoticeDTO;
import com.xinqi.modules.course.classroom.convert.AssistantContentBuild;
import com.xinqi.modules.course.classroom.convert.LiveActConvert;
import com.xinqi.modules.course.classroom.domain.LiveActEntity;
import com.xinqi.modules.course.classroom.mapper.LiveActMapper;
import com.xinqi.modules.course.classroom.service.LiveActService;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.course.clazz.service.ClassService;
import com.xinqi.modules.course.clazz.service.ClassStudentService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Objects.nonNull;

/**
 * 互动表(LiveAct)表服务实现类
 *
 * @author liuxingxing
 * @since 2023-03-31 14:16:53
 */
@Service
@RequiredArgsConstructor
public class LiveActServiceImpl extends BaseServiceImpl<LiveActMapper, LiveActEntity> implements LiveActService {

    private final ClassStudentService classStudentService;
    private final ClassService classService;

    private final LiveActConvert liveActConvert;

    private final RemoteRongyunClient remoteRongyunClient;

    private final ChatAssistantContentClient chatAssistantContentClient;

    /**
     * 随机提问-开始
     *
     * @param dto
     */
    @Override
    public void startInteraction(LiveActCreateDTO dto) {
        LiveActEntity liveAct = liveActConvert.create(dto);
        Long userId = LoginHelper.getUserId();
        liveAct.setUserId(userId);
        liveAct.setTitle("随机提问");
        this.baseMapper.insert(liveAct);
        //融云通知学生
        sendClassroomInteraction(liveAct);
    }

    /**
     * 随机提问-结束
     *
     * @param queryDTO
     */
    @Override
    public void endInteraction(InterationQueryDTO queryDTO) {
        Long classId = queryDTO.getClassId();
        Long studentId = queryDTO.getStudentId();

        // 获取所有关系成员信息
        List<ClassStudentResultDTO> classStudentResultList = classStudentService.findClassRelationStudentByClassId(classId);
        if (CollectionUtil.isEmpty(classStudentResultList)) {
            throw new RuntimeException("班级没有学生");
        }

        ClassStudentResultDTO studentResultDTO = classStudentService.findByStudentId(queryDTO.getClassId(), queryDTO.getStudentId());
        //构建消息
        NoticeDTO bean = new NoticeDTO();
        bean.setType(SysMessageEnum.ACT_END.getCode());
        Map<String, Object> content = new HashMap<String, Object>();
        content.put("type", InteractiveEnum.RANDOM.getCode());
        content.put("student_id", studentResultDTO.getStudentId());
        content.put("avatar", studentResultDTO.getAvatar());
        content.put("nickname", studentResultDTO.getStudentName());
        content.put("xinqi_number", studentResultDTO.getXinqiNumber());
        content.put("end_time", System.currentTimeMillis());
        content.put("class_id", classId);
        bean.setContent(JSON.toJSONString(content));
        bean.setClass_id(classId);
        bean.setFromuserId("0"); // 0代表系统用户
        bean.setTouserId(classId.toString());

        // 发送学生集合
        List<Long> targetIds = classStudentResultList.stream().map(ClassStudentResultDTO::getStudentId).collect(Collectors.toList());
        String[] targetIdsStr = targetIds.stream().map(x -> x + "").collect(Collectors.toList()).toArray(new String[targetIds.size()]);;

        // 发送融云停止消息
        remoteRongyunClient.creatSysUserSend(targetIdsStr, JSON.toJSONString(bean));

        // 发送助手消息
        sendAssistantMessage(studentId, classId, InteractiveEnum.RANDOM.getCode(), null);
    }

    /**
     * 点名提问
     *
     * @param queryDTO
     */
    @Override
    public void askQuestion(InterationQueryDTO queryDTO) {
        Long classId = queryDTO.getClassId();
        Long studentId = queryDTO.getStudentId();
        List<ClassStudentResultDTO> classStudentResultList = classStudentService.findRelationStudentByClassIdAndImitateStudentId(classId, studentId);

        if (CollectionUtils.isNotEmpty(classStudentResultList)) {
            classStudentResultList.forEach(userInfo -> {
                //构建消息
                NoticeDTO bean = new NoticeDTO();
                bean.setType(SysMessageEnum.ACT_END.getCode());
                Map<String, Object> content = new HashMap<>();
                content.put("type", InteractiveEnum.CALLED.getCode());
                content.put("student_id", userInfo.getId());
                content.put("avatar", userInfo.getAvatar());
                content.put("nickname", userInfo.getNickName());
                content.put("xinqi_number", userInfo.getXinqiNumber());
                content.put("end_time", System.currentTimeMillis());
                content.put("class_id", classId);
                bean.setContent(JSON.toJSONString(content));
                bean.setClass_id(classId);
                bean.setFromuserId("0"); // 0代表系统用户
                bean.setTouserId(classId.toString());
                String[] targetIds = new String[1];
                targetIds[0] = String.valueOf(userInfo.getStudentId());
                remoteRongyunClient.creatSysUserSend(targetIds, JSON.toJSONString(bean));
            });
            sendAssistantMessage(studentId, classId, InteractiveEnum.CALLED.getCode(), null);
        }
    }

    /**
     * 已废弃
     *
     * @param classId
     * @return
     */
    @Override
    public Map<String, Object> countUnread(Long classId) {
        Long userId = LoginHelper.getUserId();
        Map<String, Object> res = this.baseMapper.countUnread(userId, classId);
        Integer resourceUnread = res.get("resourceUnread") == null ? 0 : Integer.parseInt(res.get("resourceUnread").toString());
        Integer discussUnread = res.get("discussUnread") == null ? 0 : Integer.parseInt(res.get("discussUnread").toString());
        Integer examUnread = res.get("examUnread") == null ? 0 : Integer.parseInt(res.get("examUnread").toString());
        Integer homeworkUnread = res.get("homeworkUnread") == null ? 0 : Integer.parseInt(res.get("homeworkUnread").toString());
        Integer sum = resourceUnread + discussUnread + examUnread + homeworkUnread;
        res.put("allUnread", sum);
        return res;
    }

    private void sendClassroomInteraction(LiveActEntity liveAct) {
        List<ClassStudentResultDTO> classStudentList = classStudentService.findClassRelationStudentByClassId(liveAct.getClassId());
        if (classStudentList == null || classStudentList.isEmpty()) {
            throw new RuntimeException("班级没有学生");
        }
        List<Long> userIdList = classStudentList.stream().map(ClassStudentResultDTO::getStudentId).collect(Collectors.toList());
        String[] targetIds = new String[userIdList.size()];
        if (CollectionUtil.isNotEmpty(userIdList)) {
            for (int i = 0; i < userIdList.size(); i++) {
                targetIds[i] = String.valueOf(userIdList.get(i));
            }
        }
        NoticeDTO bean = new NoticeDTO();
        bean.setType(SysMessageEnum.ACT_START.getCode());
        Map<String, Object> content = new HashMap<>();
        content.put("type", InteractiveEnum.RANDOM.getCode());
        content.put("name", "课堂互动");
        content.put("class_id", liveAct.getClassId());
        content.put("end_time", System.currentTimeMillis());
        bean.setContent(JSON.toJSONString(content));
        bean.setClass_id(liveAct.getClassId());
        bean.setFromuserId("0"); // 0代表系统用户
        bean.setTouserId(liveAct.getClassId().toString());
        if (targetIds.length > 0) {
            remoteRongyunClient.creatSysUserSend(targetIds, JSON.toJSONString(bean));
        }
    }

    /**
     * 新奇助手发送课堂互动信息
     */
    private void sendAssistantMessage(Long studentId, Long classId, Integer type, Long questId) {
        List<ChatAssistantContentCreateDTO> list = new ArrayList<>();

        //查找班级课程
        ClassResultDTO dto = classService.findByClassId(classId);
        CommonErrors.INTERNAL_SERVER_ERROR.check(nonNull(dto), "班级不存在");

        QuestionsMessage questionsMessage = new QuestionsMessage();
        questionsMessage.setClassId(classId);
        questionsMessage.setTitle(null);
        questionsMessage.setContentId(1001L);
        questionsMessage.setClassRole(ClassRoleEnum.STUDENT.getCode());
        questionsMessage.setCourseName(dto.getCourseName() + Constants.SPACE_DROP + dto.getName());

        if (Objects.equals(InteractiveEnum.CALLED.getCode(), type)) {
            //点名提问
            questionsMessage.setQuestionContent("你已被老师点名提问");
            questionsMessage.setTitle("点名提问");
            type = 12;
        } else {
            //随机提问
            questionsMessage.setQuestionContent("你已被老师随机提问");
            questionsMessage.setTitle("随机提问");
            type = 11;
        }

        // 获取关系用户信息
        List<ClassStudentResultDTO> students = classStudentService.findRelationStudentByClassIdAndImitateStudentId(classId, studentId);
        for (ClassStudentResultDTO student : students) {
            list.add(AssistantContentBuild.buildCreateDTO(student.getStudentId(), AssistantTypeEnum.RELEASE.getCode(), type, null, null, JSON.toJSONString(questionsMessage), questId, null));
        }

        //发送消息
        chatAssistantContentClient.batchInsert(list);
    }


}
